package com.maezia.tdr.service.impl;

import com.maezia.tdr.common.JwtTokenProvider;
import com.maezia.tdr.common.enums.ClientStatusEnum;
import com.maezia.tdr.common.enums.DeletedTypeEnum;
import com.maezia.tdr.common.enums.StatusCodeEnum;
import com.maezia.tdr.common.exception.DriveException;
import com.maezia.tdr.dao.repository.AccessTokenRepository;
import com.maezia.tdr.domain.po.ClientDetails;
import com.maezia.tdr.domain.vo.AccessTokenVo;
import com.maezia.tdr.service.AccessTokenService;
import com.maezia.tdr.service.ClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@Service
public class AccessTokenServiceImpl implements AccessTokenService {

    @Autowired
    private AccessTokenRepository accessTokenRepository;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Override
    public AccessTokenVo getAccessToken(String clientId, String clientSecret) throws DriveException {
        ClientDetails clientDetails = clientDetailsService.getByClientId(clientId);
        if(ObjectUtils.isEmpty(clientDetails) || DeletedTypeEnum.YES.getCode() == clientDetails.getIsDeleted()){
            throw new DriveException(StatusCodeEnum.CLIENT_ID_NOT_FOUND);
        }

        if(!clientId.equals(clientDetails.getClientId())){
            throw new DriveException(StatusCodeEnum.INVALID_CLIENT_ID);
        }

        if(!clientSecret.equals(clientDetails.getClientSecret())){
            throw new DriveException(StatusCodeEnum.INVALID_CLIENT_SECRET);
        }

        if(ClientStatusEnum.LOCK.getCode() == clientDetails.getStatus()){
            throw new DriveException(StatusCodeEnum.ACCOUNT_LOCKED);
        }

        if(ClientStatusEnum.CANCEL.getCode() == clientDetails.getStatus()){
            throw new DriveException(StatusCodeEnum.ACCOUNT_DISABLED);
        }

        String accessToken = accessTokenRepository.get(clientDetails.getClientId());
        if(StringUtils.isEmpty(accessToken)){
            accessToken = jwtTokenProvider.generateToken(clientDetails);
            accessTokenRepository.save(clientDetails.getClientId(), accessToken);
        }

        Long expired = StringUtils.isEmpty(accessToken) ? 0L : accessTokenRepository.getExpired(clientDetails.getClientId());
        return new AccessTokenVo(accessToken, expired);
    }

    @Override
    public String getAccessToken(String clientId) {
        return accessTokenRepository.get(clientId);
    }
}
